
import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// 创建一个axios,并进行配置
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})
// 请求拦截器
request.interceptors.request.use(function(config) {
  // 添加token
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
    console.log(store.getters.token)
  }
  return config
}, function(err) {
  return Promise.reject(err)
})
// 响应拦截器
// 数据剥离
// 异常处理
request.interceptors.response.use(function(response) {
  const { data, success, message } = response.data
  console.log(response)
  if (success) {
    return data
  } else {
    Message({ type: 'error', message: message })
    return Promise.reject(new Error(message))
  }
}, async function(error) {
  // Message({ type: 'error', message: error.message })
  if (error.response.status === 401) {
    Message({ type: 'error', message: 'token过期' })
    await store.dispatch('user/logout')
    router.push('/login')
    return Promise.reject(error)
  }
})
export default request
